package com.zqq.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AlertDialog
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import java.lang.reflect.ParameterizedType

abstract class BaseShareFragment<VM:BaseViewModel,VB: ViewDataBinding>:Fragment() {

    protected lateinit var viewModel: VM
    protected lateinit var viewBinding: VB

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val viewId = setContentViewId()
        viewBinding = DataBindingUtil.inflate<VB>(inflater,viewId,container,false)
        viewBinding.lifecycleOwner = this
        init()
        return viewBinding.root
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initViewModel()
    }

    private fun initViewModel() {
        val type = javaClass.genericSuperclass //获取当前类的泛型超类类型信息 返回Type对象（通常是ParameterizedType实例）
        if(type != null && type is ParameterizedType){
            val actualTypeArguments = type.actualTypeArguments  // 获取泛型参数数组
            val argument = actualTypeArguments[0] //我们确定是数据第一个数据
            val tClass = argument as Class<VM>
            viewModel = ViewModelProvider(requireActivity())[tClass] //这是的区别是 需要activity的
        }
    }

    abstract fun setContentViewId(): Int
    abstract fun init()
}